var dbConfig = require('../utils/dbconfig')

// 查
getStudent = (req, res) => {
    var sql = "select * from students";
    var sqlArr = [];
    var callBack = (err, data) => {
        if (err) {
            res.send({
                code: 400,
                msg: '获取出错！',
                'list': data
            })
        } else {
            res.send({
                code: 200,
                msg: 'success',
                'list': data
            })
        }
    }
    dbConfig.sqlConnect(sql, sqlArr, callBack);
}
// 根据id查
getStudentId = (req, res) => {
    let { id } = req.query;
    var sql = "select * from students where id = ?";
    var sqlArr = [id];
    var callBack = (err, data) => {
        if (err) {
            res.send({
                code: 400,
                msg: '获取出错！',
            })
        } else {
            res.send({
                code: 200,
                msg: 'success',
                'list': data
            })
        }
    }
    dbConfig.sqlConnect(sql, sqlArr, callBack);
}
// 增加
addStudent = (req, res) => {
    let { head_img, name, age, sex, intro } = req.body;
    console.log(req.body)
    var sql = "insert into students(id,head_img,name,age,sex,intro) value (?,?,?,?,?,?)";
    var sqlArr = [Math.random().toString(36).substr(-10), head_img, name, age, sex, intro];
    var callBack = (err, data) => {
        if (err) {
            res.send({
                code: 400,
                msg: '添加失败',
            })
        } else {
            res.send({
                code: 200,
                msg: '添加成功',
            })
        }
    }
    dbConfig.sqlConnect(sql, sqlArr, callBack);
}
// 删除
// 增加
deleteStudent = (req, res) => {
    let { id } = req.query;
    let sql = 'delete from students where id = ?'
    let sqlArr = [id]
    var callBack = (err, data) => {
        if (err) {
            res.send({
                code: 400,
                msg: '删除失败！！'
            })
        } else {
            res.send({
                code: 200,
                msg: '删除成功！！',
            })
        }
    }
    dbConfig.sqlConnect(sql, sqlArr, callBack);
}
// 修改
editStudent = (req, res) => {
    let { id,head_img,name,age,sex,intro } = req.body;
    let sql = 'update students set head_img=?,name=?,age=?,sex=?,intro=?where id = ?'
    let sqlArr = [head_img,name,age,sex,intro,id]
    var callBack = (err, data) => {
        if (err) {
            console.log(err)
            res.send({
                code: 400,
                msg: '更改失败！！'
            })
        } else {
            res.send({
                code: 200,
                msg: '更改成功！！',
            })
        }
    }
    dbConfig.sqlConnect(sql, sqlArr, callBack);
}
module.exports = {
    getStudent,
    getStudentId,
    addStudent,
    deleteStudent,
    editStudent
}  